<?php

namespace app\api\controller;

use app\common\BaseApiController;
use think\facade\Db;
use app\api\middleware\Auth as MiddlewareAuth;
use app\common\Result;

class User extends BaseApiController
{

    protected $middleware = [
        MiddlewareAuth::class
    ];

    public function detail()
    {
        // 获取用户ID 从token中获取
        $uid = $this->request->uid;

        // 查询用户信息
        $user = Db::table('user')->where('id', $uid)->find();

        if (!$user) {
            return Result::error('用户不存在');
        }

        // 返回用户信息
        return Result::success($user, '获取详情成功');
    }

    public function edit()
    {
        $uid = $this->request->uid;
        $data = $this->request->post();

        // 验证参数
        $validate = new \app\validate\UserEdit();
        if (!$validate->check($data)) {
            return Result::error($validate->getError());
        }

        // 查询用户信息
        $user = Db::table('user')->where('id', $uid)->find();

        if (!$user) {
            return Result::error('用户不存在');
        }

        // 更新用户信息
        $updateData = [
            'nickname' => $data['nickname'] ?? $user['nickname'], // 昵称
            'avatar' => $data['avatar'] ?? $user['avatar'], // 头像
        ];

        Db::table('user')->where('id', $uid)->update($updateData);

        return Result::success(null, '更新成功');
    }
}
